<template>
  <MyBigDialog title="Import" >
    <q-card class="q-pa-md config-card">
      <q-form @submit="onSubmitConfig" class="q-gutter-md">
        <div class="config-card-title text-primary cap">
          1. Upload CSV {{ title }}
        </div>
        <label for="file1"> Upload a file</label>
        <input
          type="file"
          required
          id="file1"
          name="file"
          accept=".csv"
        /><br /><br />
        <div style="text-align: center;">
          <q-btn label="Submit" type="submit" class="yellow-btn" />
        </div>
      </q-form>
    </q-card>
  </MyBigDialog>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import MyBigDialog from 'src/components/container/MyBigDialog.vue';
import { importPartsMaster, importStockMaster } from 'src/services/uploadService';
import {  ref } from 'vue';

const props = defineProps<{
  mode: 'parts' | 'stocks'
}>()
const q = useQuasar();

const title = ref('')

const emit = defineEmits(['update'])

async function onSubmitConfig(e: Event) {
  if (props.mode=='stocks'){
    importStock(e)
  }
  if (props.mode=='parts'){
    importParts(e)
  }
}

async function importStock(e: any) {
  try {
    let file = e.target.file.files[0];
    const res = await importStockMaster({ file });
    if (res.data.code==1) {
       q.notify({
        message: 'success',
        color: 'positive',
      });
      emit('update')
    }
  } catch (error) {
    console.log(error);
    return q.notify({
      message: 'fail',
      color: 'negative',
    });
  }
}

async function importParts(e:any) {
  try {
    let file = e.target.file.files[0];
    const res = await importPartsMaster({ file });
    if (res.data.code==1) {
       q.notify({
        message: 'success',
        color: 'positive',
      });
      emit('update')
    }
  } catch (error) {
    console.log(error);
    return q.notify({
      message: 'fail',
      color: 'negative',
    });
  }
}

function init(){
  if (props.mode=='stocks'){
    title.value = 'stock item master'
  }
  if (props.mode=='parts'){
    title.value = 'parts master'
  }
}
init()
</script>
